#!/bin/sh -e

SRCDIR=$1 ; shift
OBJDIR=$1 ; shift
dirs=$1

if test $(cd ${SRCDIR} ; pwd) = $(cd ${SRCDIR} ; cd ${OBJDIR} ; pwd)
then
	echo "failed. ${OBJDIR} == ${SRCDIR}"
	exit 1
fi

cd ${SRCDIR}
mkdir -p ${OBJDIR}

# Generate sub-directories first

find ${dirs} -type d -print | while read dirname
do
    if test -r $dirname/Makefile
    then
	(
	    echo Generating ${OBJDIR}/$dirname/Makefile
	    cd ${OBJDIR}
	    mkdir -p $dirname
	    cd $dirname

	    top_builddir=$(echo $dirname | sed -e 's;[^/]*;..;g')

	    cat <<EOF >Makefile.tmp
# Generated by $0

# define autoconf style names such as srcdir, builddir, abs_srcdir,
# top_srcdir, abs_top_srcdir, ...
include ${top_builddir}/../mk/dirs.mk

include \${srcdir}/Makefile
EOF
	    mv Makefile.tmp Makefile
	)
    fi
done

# OBJDIR makefile is just different enough

cat <<EOF > $OBJDIR/Makefile.tmp
# Generated by $0

# define autoconf style names such as srcdir, builddir, abs_srcdir,
# top_srcdir, abs_top_srcdir, ...
include ../mk/dirs.mk

programs config man install clean install-programs:
	set -e ; \\
	for d in \$(SUBDIRS) ; \\
	do \\
		( cd \$\$d && \$(MAKE) \$@ ) ; \\
	done
EOF

mv $OBJDIR/Makefile.tmp $OBJDIR/Makefile
